<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
// @ts-ignore
import { ReadClients, WriteClients } from '@/Urls/AxiosHelper'

const router = useRouter()

const readClient = ReadClients[3]
const writeClient = WriteClients[3]

type BomItem = {
  id: number | string
  bomNumber: string
  version: string
  productName: string
  productNumber: string
  specificationModel: string
  unit: string
  isDefaultBom: boolean
  dailyOutput: number
}

const queryForm = reactive({
  bomNumber: '',              // BOM编号
  productKeyword: '',         // 产品名称/编号/规格型号
  version: '',               // BOM版本号
})

// 控制"更多"展开/收起
const showMore = ref(false)

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

const loading = ref(false)
const tableData = ref<BomItem[]>([])

async function fetchList() {
  loading.value = true
  try {
    const res = await readClient.get('/productread/api/Bom/BomShow', {
      params: {
        pageIndex: pagination.pageIndex,
        pageSize: pagination.pageSize,
        bomNumber: queryForm.bomNumber,
        productKeyword: queryForm.productKeyword,
        version: queryForm.version,
      }
    })
    
    console.log('BOM接口响应:', res?.data)
    
    const payload = res?.data
    let items = []
    let total = 0
    
    // 处理不同的数据结构
    if (Array.isArray(payload)) {
      items = payload
    } else if (payload?.data) {
      if (Array.isArray(payload.data)) {
        items = payload.data
      } else if (payload.data.data && Array.isArray(payload.data.data)) {
        // 处理嵌套的data.data结构
        items = payload.data.data
        total = payload.data.totalCount || payload.data.total || 0
      } else if (payload.data.items) {
        items = payload.data.items
        total = payload.data.totalCount || payload.data.total || 0
      } else if (payload.data.rows) {
        items = payload.data.rows
        total = payload.data.totalCount || payload.data.total || 0
      } else if (payload.data.list) {
        items = payload.data.list
        total = payload.data.totalCount || payload.data.total || 0
      }
    } else if (payload?.items) {
      items = payload.items
      total = payload.total || 0
    } else if (payload?.rows) {
      items = payload.rows
      total = payload.total || 0
    } else if (payload?.list) {
      items = payload.list
      total = payload.total || 0
    }
    
    // 确保items是数组
    if (!Array.isArray(items)) {
      console.warn('items不是数组:', items)
      items = []
    }
    
    console.log('处理后的items:', items)
    
    tableData.value = items.map((item: any, index: number) => ({
      id: item.id || index + 1,
      bomNumber: item.bomNumber || '',
      version: item.bomVersion || '',
      productName: item.productName || '',
      productNumber: item.productNumber || '',
      specificationModel: item.specificationModel || '',
      unit: item.unit || '',
      isDefaultBom: item.isDefaultBom || false,
      dailyOutput: item.dailyOutput || 0,
      remarks: item.remarks || '',
      materialAccessories: item.materialAccessories || '',
      processRouteNumber: item.processRouteNumber || '',
    }))
    
    pagination.total = total
    console.log('最终表格数据:', tableData.value)
  } catch (err) {
    console.error('获取BOM列表失败:', err)
    ElMessage.error('获取BOM列表失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  pagination.pageIndex = 1
  fetchList()
}

function handleReset() {
  Object.assign(queryForm, {
    bomNumber: '',
    productKeyword: '',
    version: '',
  })
  pagination.pageIndex = 1
  fetchList()
}

function handleCreate() { 
  router.push({ name: 'BomCreate' })
}

function handleDetail(row: BomItem) { 
  router.push({ name: 'BomDetail', query: { bomNumber: row.bomNumber } })
}

function handleEdit(row: BomItem) { 
  router.push({ name: 'BomEdit', query: { bomNumber: row.bomNumber, origin: 'list' } })
}

function handleCopy(row: BomItem) {
  ElMessage.info('复制功能待实现')
}

async function handleDelete(row: BomItem) {
  try {
    await ElMessageBox.confirm(`确认删除【${row.bomNumber}】吗？`, '提示', { type: 'warning' })
    await writeClient.get('/api/Bom/DeleteBom', { params: { Id: row.id } })
    ElMessage.success('删除成功')
    fetchList()
  } catch (err: any) {
    if (err === 'cancel' || err?.message === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      console.error('删除失败:', err)
      ElMessage.error('删除失败')
    }
  }
}

function handleImport() { 
  ElMessage.info('导入功能待实现') 
}

async function handleExport() {
  try {
    const url = `${readClient.defaults.baseURL}/api/Bom/Export`
    window.location.href = url
    ElMessage.success('导出成功')
  } catch { 
    ElMessage.error('导出失败') 
  }
}

function handlePageChange(page: number) {
  pagination.pageIndex = page
  fetchList()
}

function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchList()
}

onMounted(fetchList)
</script>

<template>
  <div class="bom-info-wrap">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <div class="search-row">
        <el-input 
          v-model="queryForm.bomNumber" 
          placeholder="请输入BOM编号" 
          clearable 
          class="search-input"
        />
        <el-input 
          v-model="queryForm.productKeyword" 
          placeholder="请输入产品名称/编号/规格型号" 
          clearable 
          class="search-input"
        />
        <el-input 
          v-model="queryForm.version" 
          placeholder="请输入BOM版本号" 
          clearable 
          class="search-input"
        />
        <div class="search-actions">
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
      </div>
    </el-card>

    <!-- 主内容区 -->
    <el-card class="content-card">
      <template #header>
        <div class="content-header">
          <h2 class="content-title">BOM管理</h2>
          <div class="action-buttons">
            <el-button type="primary" @click="handleCreate">新增</el-button>
            <el-button @click="handleDelete">删除</el-button>
          </div>
        </div>
      </template>

      <el-table :data="tableData" v-loading="loading" class="bom-table">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" width="80" align="center">
          <template #default="scope">{{ (pagination.pageIndex-1)*pagination.pageSize + scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column prop="bomNumber" label="BOM编号" min-width="180">
          <template #default="scope">
            <el-link type="primary" underline="hover" @click="handleDetail(scope.row)">{{ scope.row.bomNumber }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="version" label="版本号" width="100" align="center" />
        <el-table-column prop="productName" label="产品名称" min-width="160" show-overflow-tooltip />
        <el-table-column prop="productNumber" label="产品编号" min-width="140" show-overflow-tooltip />
        <el-table-column prop="specificationModel" label="规格型号" min-width="140" show-overflow-tooltip />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column label="默认BOM" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isDefaultBom ? 'success' : 'info'">
              {{ scope.row.isDefaultBom ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dailyOutput" label="日产量" width="100" align="center" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-link type="primary" underline="never" @click="handleEdit(scope.row)">编辑</el-link>
            <el-divider direction="vertical" />
            <el-link type="primary" underline="never" @click="handleCopy(scope.row)">复制</el-link>
            <el-divider direction="vertical" />
            <el-link type="danger" underline="never" @click="handleDelete(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <div class="pagination-info">共{{ pagination.total }}条</div>
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="sizes, prev, pager, next, jumper"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.bom-info-wrap {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 搜索卡片样式 */
.search-card {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.search-card :deep(.el-card__body) {
  padding: 20px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  min-width: 200px;
  max-width: 300px;
}

.search-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-shrink: 0;
}

/* 内容卡片样式 */
.content-card {
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.content-card :deep(.el-card__header) {
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 16px 20px;
}

.content-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.content-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-buttons .el-button {
  font-weight: 500;
  padding: 10px 20px;
  border-radius: 4px;
}

/* 表格样式 */
.bom-table {
  width: 100%;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.bom-table :deep(.el-table__header) {
  background: #f5f7fa;
}

.bom-table :deep(.el-table__header th) {
  background: transparent;
  color: #606266;
  font-weight: 600;
  border: none;
  padding: 12px 8px;
  font-size: 14px;
}

.bom-table :deep(.el-table__body tr:hover) {
  background: #f5f7fa;
}

.bom-table :deep(.el-table__body td) {
  border: 1px solid #ebeef5;
  padding: 12px 8px;
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

/* 分页样式 */
.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 16px 0;
}

.pagination-info {
  color: #606266;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-section,
  .content-section {
    padding: 16px;
  }
  
  .search-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    min-width: auto;
    max-width: none;
  }
  
  .search-actions {
    justify-content: center;
  }
  
  .content-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .pagination-section {
    flex-direction: column;
    gap: 16px;
  }
}
</style>
